package com.streamer.app.fragment

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.widget.EditText
import android.util.Log
import android.view.Gravity
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.streamer.app.R
import com.streamer.app.ThreePaneLiveActivity
import com.streamer.app.adapter.ChatAdapter
import com.streamer.app.adapter.EmojiAdapter
import com.streamer.app.bean.LiveBean
import com.streamer.app.bean.MessageBean
import com.streamer.app.databinding.FragmentChatBinding
import com.streamer.app.utils.MqttManager
import com.streamer.app.utils.UserManager.getLocalUser
import kotlin.random.Random

class ChatFragment : BaseFragment<FragmentChatBinding>(), MqttManager.MessageCallback {
    private lateinit var rvDanmaku: RecyclerView
    private lateinit var danmakuAdapter: ChatAdapter
    private var etSend: EditText? = null
    private var globalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
    private var mliveData: LiveBean? = null


    // 自定义表情面板（新方案）
    private var emojiContainer: View? = null
    private var isEmojiPanelVisible = false

    // MQTT相关
    private lateinit var mqttManager: MqttManager


    override fun initView() {
        mliveData =
            (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arguments?.getSerializable(ARG_LIVE_DATA, LiveBean::class.java)
            } else {
                @Suppress("DEPRECATION")
                arguments?.getSerializable(ARG_LIVE_DATA)
            }) as LiveBean?
        initViews(_binding.root)
    }

    private fun initViews(root: View) {
        setupMqtt()
        // 初始化弹幕列表
        rvDanmaku = root.findViewById(R.id.rv_danmaku)
        danmakuAdapter = ChatAdapter(mutableListOf())
        rvDanmaku.apply {
            layoutManager = LinearLayoutManager(requireContext()).apply {
                stackFromEnd = true
            }
            adapter = danmakuAdapter
        }
        // 输入框
        etSend = root.findViewById(R.id.etSend)
        val inputBar = root.findViewById<View>(R.id.input_bar)

        // 软键盘弹出时顶起输入栏（使用调整布局大小）
        requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        // 监听键盘显示与隐藏，显示时滚动到底部
        val view = root
        globalLayoutListener = object : ViewTreeObserver.OnGlobalLayoutListener {
            private var lastHeight = 0
            override fun onGlobalLayout() {
                val currentHeight = view.height
                if (lastHeight != 0 && currentHeight != lastHeight) {
                    val heightDiff = lastHeight - currentHeight
                    if (heightDiff > 200) {
                        // 键盘显示
                        Log.d("ChatFragment", "Soft keyboard shown")
                        rvDanmaku.post {
                            rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
                        }
                    }
                }
                lastHeight = currentHeight
            }
        }
        view.viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener)

        // 使用WindowInsets精确抬升输入栏，避免被键盘遮挡
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val imeBottom = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
            val navBottom = insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom
            val translation = (imeBottom - navBottom).coerceAtLeast(0)
            inputBar.translationY = -translation.toFloat()
            // 为列表预留底部空间
            rvDanmaku.setPadding(
                rvDanmaku.paddingLeft,
                rvDanmaku.paddingTop,
                rvDanmaku.paddingRight,
                translation + inputBar.height
            )
            insets
        }

        // 发送键处理（与 Activity 行为一致）
        etSend?.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                val text = etSend?.text?.toString()?.trim().orEmpty()
                if (text.isNotEmpty()) {
                    viewMode.send(text, mliveData?.id.toString())
                    rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
                    etSend?.setText("")
                }
                true
            } else {
                false
            }
        }
        // 历史消息/新消息观察
        viewMode.MessageListLV.observe(requireActivity()) { result ->
            result?.data?.let { list ->
                danmakuAdapter.setAll(list)
                rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
            }
        }
        _binding.tvIcon.setOnClickListener {
            toggleEmojiPanel()
        }
    }

    companion object {
        private const val ARG_LIVE_DATA = "liveData"
        fun newInstance(mliveData: LiveBean?): ChatFragment {
            val f = ChatFragment()
            val b = Bundle()
            b.putSerializable(ARG_LIVE_DATA, mliveData)
            f.arguments = b
            return f
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        view?.viewTreeObserver?.let { vto ->
            globalLayoutListener?.let { vto.removeOnGlobalLayoutListener(it) }
        }
        globalLayoutListener = null
        etSend = null
    }


    private fun setupMqtt() {
        mqttManager = MqttManager.getInstance()
        mqttManager.addMessageCallback(this)
        val random6Digit = Random.nextInt(100000, 1000000)
        // 连接MQTT
        mqttManager.connect(
            requireActivity(),
            "${mliveData?.liveRoomNo + "," + mliveData?.id + "," + getLocalUser()?.id + ",5" + "," + random6Digit}"
        )
        { success, message ->
            requireActivity().runOnUiThread {
                if (success) {
                    Log.d("xxxx", "MQTT connected: $message")
                    // 订阅直播相关主题
                    subscribeToLiveTopics()
                } else {
                    Log.e("xxxx", "MQTT connection failed: $message")
                    Toast.makeText(
                        requireActivity(), "MQTT连接失败: $message", Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    private fun subscribeToLiveTopics() {
        // 订阅直播相关主题
        val liveRoomNo = mliveData?.id ?: ""
        val topics = listOf(
            "chat/$liveRoomNo",      // 聊天消息
        )

        topics.forEach { topic ->
            mqttManager.subscribe(topic) { success, message ->
                requireActivity().runOnUiThread {
                    if (success) {
                        Log.d("LiveStreamActivity", "Subscribed to $topic")
                    } else {
                        Log.e("LiveStreamActivity", "Failed to subscribe to $topic: $message")
                    }
                }
            }
        }
    }

    // MQTT消息回调
    override fun onMessageReceived(topic: String, message: String) {
        Log.d("LiveStreamActivity", "MQTT message - Topic: $topic, Message: $message")

        requireActivity().runOnUiThread {
            handleLiveMessage(message)
        }
    }

    private fun handleLiveMessage(message: String) {
        try {
            val gson = Gson()
            val chatMessage = gson.fromJson(message, MessageBean::class.java)

            when (chatMessage.type) {
                1 -> { /* JOIN(1) - 进入房间 */
                }

                2 -> { /* LEAVE(2) - 离开房间 */
                }

                3 -> { // MSG(3) - 普通消息
                    // 添加到弹幕适配器
                    if(chatMessage.range==0){
                        danmakuAdapter.append(chatMessage)
                        // 滚动到最新消息
                        rvDanmaku.post {
                            rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
                        }
                    }
                }

                4 -> { /* SYSTEM(4) - 系统消息 */
                }

                5 -> { /* DRAW(5) - 抽奖倒计时 */
                }

                6 -> { /* COUPON(6) - 优惠券倒计时 */
                }

                7 -> { /* TAUGHT(7) - 商品讲解 */
                }

                8 -> { /* NOTICE(8) - 公告 */
                }

                9 -> { /* COUPON_RECEIVE(9) - 优惠券领取 */
                }

                10 -> { /* DRAW_USER(10) - 抽奖完成通知 */
                }

                11 -> { /* MSG_CONCEAL(11) - 消息隐藏 */
                }

                12 -> { /* BESTOW_GIFT(12) - 赠送礼物 */
                }

                13 -> { /* DEFRIEND(13) - 踢出直播间 */
                }

                14 -> { /* POINTS_ACQUISITION(14) - 获取积分 */
                }

                15 -> { /* CANCEL_TAUGHT(15) - 取消讲解 */
                }

                16 -> { /* LIKE(16) - 点赞 */
                    ( context as ThreePaneLiveActivity).setLikeNumber(chatMessage.content)

                }

                17 -> { /* PUTAWAY(17) - 商品上架 */
                }

                18 -> { /* CONFIG_STATUS_UPDATE(18) - 直播配置状态更新 */
                }

                19 -> { /* THE_USER_IS_BUYING(19) - 正在购买商品 */
                }

                20 -> { /* POPULARITY(20) - 直播间人气推送 */
//                    tvViewerCount.text = chatMessage.content.toString() + "人"

                }

                else -> { /* 未知类型 */
                }
            }

        } catch (e: JsonSyntaxException) {
            Log.e("LiveStreamActivity", "Error parsing JSON message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error handling message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        }
    }


    override fun onConnectionStatusChanged(connected: Boolean) {
        Log.d("LiveStreamActivity", "MQTT connection status changed: $connected")

    }


    private fun toggleEmojiPanel() {
        if (isEmojiPanelVisible) {
            hideEmojiPanel()
        } else {
            showEmojiPanel()
        }
    }

    private fun showEmojiPanel() {
        // 收起系统键盘
        val imm =
            requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(etSend?.windowToken, 0)

        if (emojiContainer == null) {
            val root = requireActivity().findViewById<ViewGroup>(android.R.id.content)

            val panelView = layoutInflater.inflate(R.layout.bottom_sheet_emoji, root, false)
            // 使用布局文件中定义的高度，而不是硬编码
            val panelHeight = (400 * resources.displayMetrics.density).toInt()
            val lp = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, panelHeight)
            lp.gravity = Gravity.BOTTOM
            panelView.layoutParams = lp

            // 设置数据
            val llMostUsed = panelView.findViewById<LinearLayout>(R.id.ll_most_used)
            val rvAllEmojis = panelView.findViewById<RecyclerView>(R.id.rv_all_emojis)
            val mostUsedEmojis = listOf(
                "\uD83D\uDE04",
                "\uD83D\uDE06",
                "\uD83D\uDE02",
                "\uD83E\uDD23",
                "\uD83D\uDE0D",
                "\uD83E\uDD70",
                "\uD83D\uDE0E",
                "\uD83E\uDD14",
            )
            val allEmojis = listOf(
                "😊",
                "😘",
                "🥺",
                "😠",
                "🤭",
                "😭",
                "😡",
                "😄",
                "😅",
                "😌",
                "😜",
                "😝",
                "🐕",
                "❤️",
                "🤏",
                "👏",
                "🙏",
                "🤗",
                "🌹",
                "😅",
                "🤩",
                "⭐",
                "👤",
                "🤔",
                "🥺",
                "🙂"
            )
            llMostUsed.removeAllViews()
            mostUsedEmojis.forEach { emoji ->
                val tv = TextView(requireActivity()).apply {
                    text = emoji
                    textSize = 24f
                    gravity = Gravity.CENTER
                    setPadding(16, 16, 16, 16)
                    background =
                        requireActivity().getDrawable(android.R.drawable.list_selector_background)
                    setOnClickListener {
                        insertEmojiToInput(emoji)
                        hideEmojiPanel()
                    }
                }
                val p = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
                p.setMargins(4, 4, 4, 4)
                llMostUsed.addView(tv, p)
            }
            rvAllEmojis.layoutManager = GridLayoutManager(requireActivity(), 6)
            rvAllEmojis.adapter = EmojiAdapter(allEmojis) { emoji ->
                insertEmojiToInput(emoji)
                hideEmojiPanel()
            }
            // 强制RecyclerView重新测量和布局
            rvAllEmojis.requestLayout()
            // 添加到根布局
            root.addView(panelView)
            emojiContainer = panelView
        }

        // 上推输入栏到面板之上
        val panelHeight = (emojiContainer?.layoutParams?.height ?: 0)
        val inputBar = _binding.root.findViewById<View>(R.id.input_bar)
        inputBar.animate().translationY(-panelHeight.toFloat()).setDuration(200)
            .setInterpolator(AccelerateDecelerateInterpolator()).start()
        emojiContainer?.visibility = View.VISIBLE
        isEmojiPanelVisible = true
    }

    /**
     * 将emoji插入到输入框
     */
    private fun insertEmojiToInput(emoji: String) {
        val currentText = etSend?.text.toString()
        val cursorPosition: Int = etSend?.selectionStart!!.toInt()
        val newText =
            currentText.substring(0, cursorPosition) + emoji + currentText.substring(cursorPosition)
        etSend?.setText(newText)
        etSend?.setSelection(cursorPosition + emoji.length)

        // 确保输入框获得焦点
        etSend?.requestFocus()
    }

    private fun hideEmojiPanel() {
        emojiContainer?.let { view ->
            view.visibility = View.GONE
        }
        val inputBar = _binding.root.findViewById<View>(R.id.input_bar)
        inputBar.animate().translationY(0f).setDuration(200)
            .setInterpolator(AccelerateDecelerateInterpolator()).start()
        isEmojiPanelVisible = false
    }
} 